﻿using Furion;
using Furion.DatabaseAccessor;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using StackExchange.Profiling.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Sms.V20210111;
using TencentCloud.Sms.V20210111.Models;
using TulingMember.Core; 

namespace TulingMember.Application
{
    public class SmsService : IDynamicApiController
    {
        private static string AppID = App.GetConfig<string>("Sms:AppID");
        private static string AppKey = App.GetConfig<string>("Sms:AppKey");
        private static string SecretId = App.GetConfig<string>("Sms:SecretId");
        private static string SecretKey = App.GetConfig<string>("Sms:SecretKey");
        private static string SignName = App.GetConfig<string>("Sms:SignName");
        private static string TemplateIdRegist = App.GetConfig<string>("Sms:TemplateIdRegist");
        private readonly IRepository<User> _userRepository;
        ILogger<SmsService> _logger;
        public SmsService(ILogger<SmsService> logger, IRepository<User> userRepository)
        {
            _logger = logger;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 发送注册验证码
        /// </summary> 
        [HttpPost]
        [AllowAnonymous]
        public Task SendRegistCode(string phone)
        {
            var oldUser = _userRepository.Where(m => m.Account == phone &&!m.IsDeleted,false,true).FirstOrDefault();
            if (oldUser != null)
            {
                throw Oops.Bah(ErrorCode.WrongValidation, "该手机号已注册").StatusCode(ErrorStatus.ValidationFaild);
            }
            var codeKey = AppStr.RegistCodeKey + "_" + phone;
            var registCode= RedisHelper.GetString(codeKey);
           
            if (!string.IsNullOrEmpty(registCode))
            {
                throw Oops.Bah("验证码已发送，请勿重复发送").StatusCode(ErrorStatus.ValidationFaild);
            }
            registCode = new Random().Next(100000, 999999).ToString();
            RedisHelper.SetString(codeKey, registCode, new TimeSpan(0, 5, 0));
            Credential cred = new()
            {
                SecretId = SecretId,
                SecretKey = SecretKey
            };


            HttpProfile httpProfile = new()
            {
                Endpoint = ("sms.tencentcloudapi.com"),
            };
            ClientProfile clientProfile = new()
            {
                HttpProfile = httpProfile
            };

            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            SendSmsRequest req = new SendSmsRequest()
            {
                PhoneNumberSet = new string[] { phone },
                SmsSdkAppId = AppID,
                SignName = SignName,               
                TemplateId = TemplateIdRegist,
                TemplateParamSet = new string[] { registCode, "5" }
            }; 
            SendSmsResponse resp = client.SendSmsSync(req);
            _logger.LogInformation("发送注册验证码返回数据：" + resp.ToJson());
            if (!"Ok".Equals(resp.SendStatusSet[0].Code))
            {
                RedisHelper.KeyDelete(codeKey);
                throw Oops.Bah("验证码发送失败："+ resp.SendStatusSet[0].Message).StatusCode(ErrorStatus.ValidationFaild);
            }            
            return Task.CompletedTask;
        }

        /// <summary>
        /// 发送注册验证码
        /// </summary> 
        [HttpPost]
        [AllowAnonymous]
        public Task SendForgetPwdCode(string phone)
        {
            var oldUser = _userRepository.Where(m => m.Account == phone && !m.IsDeleted, false, true).FirstOrDefault();
            if (oldUser == null)
            {
                throw Oops.Bah(ErrorCode.WrongValidation, "该手机号未注册").StatusCode(ErrorStatus.ValidationFaild);
            }
            var codeKey = AppStr.ForgetPwdCodeKey + "_" + phone;
            var registCode = RedisHelper.GetString(codeKey);

            if (!string.IsNullOrEmpty(registCode))
            {
                throw Oops.Bah("验证码已发送，请勿重复发送").StatusCode(ErrorStatus.ValidationFaild);
            }
            registCode = new Random().Next(100000, 999999).ToString();
            RedisHelper.SetString(codeKey, registCode, new TimeSpan(0, 5, 0));
            Credential cred = new()
            {
                SecretId = SecretId,
                SecretKey = SecretKey
            };


            HttpProfile httpProfile = new()
            {
                Endpoint = ("sms.tencentcloudapi.com"),
            };
            ClientProfile clientProfile = new()
            {
                HttpProfile = httpProfile
            };

            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            SendSmsRequest req = new SendSmsRequest()
            {
                PhoneNumberSet = new string[] { phone },
                SmsSdkAppId = AppID,
                SignName = SignName,
                TemplateId = TemplateIdRegist,
                TemplateParamSet = new string[] { registCode, "5" }
            };
            SendSmsResponse resp = client.SendSmsSync(req);
            _logger.LogInformation("发送忘记密码验证码返回数据：" + resp.ToJson());
            if (!"Ok".Equals(resp.SendStatusSet[0].Code))
            {
                RedisHelper.KeyDelete(codeKey);
                throw Oops.Bah("验证码发送失败：" + resp.SendStatusSet[0].Message).StatusCode(ErrorStatus.ValidationFaild);
            }
            return Task.CompletedTask;
        }
    }
}
